const router = require("koa-router")();
const DB = require("../../module/db");
const sd = require("silly-datetime");

router.get("/", async (ctx) => {
    ctx.body = "review首页";

}).post("/addProject", async (ctx) => {
    let data = ctx.request.body;
    let list = {
        "name": (data.name.length > 0) ? data.name : "新的项目",
        "userId": data.userId,
        "reviews": [],
        "collections": [],
        "introduction": (data.introduction.length > 0) ? data.introduction : "欢迎来到我的新项目..."
    }
    let result = await DB.insert('project', list);
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    try {
        if (result.result.ok) {
            // console.log(result.ops[0]._id)
            ctx.body = 1;
            console.log(time + "：添加项目成功" + data.name);
        } else {
            ctx.body = "添加项目失败";
        }
    } catch (e) {
        ctx.body = e;
        console.log(time + "：" + e);
    }

}).get("/getProject", async (ctx) => {
    ctx.body = await DB.find('project', {"userId": ctx.query["userId"]});

}).post("/updateProject", async (ctx) => {
    // console.log(ctx.request.body)
    let data = await DB.update('project', {"_id": DB.getObjectId(ctx.request.body.id)}, {"name": ctx.request.body.name, "introduction": ctx.request.body.introduction})
    if (data.result.ok)
        ctx.body = 1
    else
        ctx.body = 0

}).post("/deleteProject", async (ctx) => {
    let id = ctx.request.body.id
    let reviews = ctx.request.body.reviews
    let flag = true
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    for (let j = 0; j < reviews.length; j ++) {
        let data = await DB.findSomeCol('review', {'_id': DB.getObjectId(reviews[j])}, {"_id": 0, "mediaId": 1});
        let mediaIdList = data[0].mediaId
        for (let i = 0; i < mediaIdList.length; i ++) {
            let data0 = await DB.findSomeCol('media', {'_id': DB.getObjectId(mediaIdList[i])}, {"_id": 0, "fileId": 1});
            let fileId = data0[0].fileId;
            let data1 = await DB.remove1('media', {"_id": DB.getObjectId(mediaIdList[i])});
            if (data1.result.ok) {
                let data2 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
                let data3 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
                if (data2.result.ok && data3.result.ok) {
                    let data4 = await DB.remove2('comment', {"mediaId": mediaIdList[i]});
                    let data5 = await DB.findSomeCol('tagging', {'mediaId': mediaIdList[i]}, {"_id": 0, "fileId": 1});
                    if (data5.length > 0) {
                        let fileId2 = data5[0]["fileId"];
                        let data6 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId2)});
                        let data7 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId2)});
                        let data8 = await DB.remove1('tagging', {'mediaId': mediaIdList[i]});
                        if (!(data6.result.ok && data7.result.ok && data8.result.ok))
                            flag = false
                    }
                    flag = flag && data4.result.ok
                } else
                    flag = false
            } else
                flag = false
        }
        if (flag) {
            let result = await DB.remove1('review', {"_id": DB.getObjectId(reviews[j])})
            if (!result.result.ok)
                flag = false
        }
    }
    if (flag) {
        let result2 = await DB.remove1('project', {"_id": DB.getObjectId(id)})
        if (result2.result.ok) {
            ctx.body = {
                type: 1,
                info: "删除项目成功"
            };
            console.log(time + "：删除项目成功");
        } else {
            ctx.body = {
                type: 0,
                info: "删除项目失败"
            };
            console.log(time + "：删除项目成功");
        }
    } else {
        ctx.body = {
            type: 0,
            info: "删除项目失败"
        };
        console.log(time + "：删除项目成功");
    }

}).get("/getProjectCount", async (ctx) => {
    let projectCount = await DB.count('project', {"userId": ctx.query["userId"]});
    let reviewCount = 0
    let reviewsList = await DB.findSomeCol('project', {"userId": ctx.query["userId"]}, {"_id": 0, "reviews": 1});
    for (let i = 0; i < reviewsList.length; i ++)
        reviewCount += reviewsList[i].reviews.length
    let collectionsCount = 0
    let collectionsList = await DB.findSomeCol('project', {"userId": ctx.query["userId"]}, {"_id": 0, "collections": 1});
    for (let i = 0; i < collectionsList.length; i ++)
        collectionsCount += collectionsList[i].collections.length
    // console.log(projectCount, reviewCount, collectionsCount)
    ctx.body = {
        projectCount: projectCount,
        reviewCount: reviewCount,
        collectionsCount: collectionsCount,
    }

}).post("/getProjectDetail", async (ctx) => {
    let reviews = ctx.request.body.reviews
    let collections = ctx.request.body.collections
    let list = []
    for (let i = 0; i < reviews.length; i ++) {
        let data = await DB.findSomeCol('review', {"_id": DB.getObjectId(reviews[i])}, {"userId": 0})
        data[0].type = "任务"
        list.push(data[0])
    }
    for (let i = 0; i < collections.length; i ++) {
        let data = await DB.findSomeCol('review', {"_id": DB.getObjectId(collections[i])}, {"userId": 0, "mediaId": 0})
        data[0].type = "收藏"
        list.push(data[0])
    }
    ctx.body = {
        list: list
    }

});

module.exports = router.routes();
